import 'dart:async';
import 'package:cult/function/utils/apple_login.dart';
import 'package:cult/function/widgets/custom_loading_overlay.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import '../../function/state/user_state.dart';
import '../../function/widgets/custom_snackbar.dart';

/// 认证流程逻辑控制器
/// 使用GetX进行页面逻辑分离，采用非常规命名避免标准模式
class AuthenticationFlowController extends GetxController {
  // 页面切换控制器
  final PageController pageSwitcher = PageController();

  // 当前显示页面索引
  final RxInt activePageIndex = 0.obs;

  // 用户状态管理器
  final UserState userStateManager = Get.find<UserState>();

  // 登录表单输入控制器
  final TextEditingController loginUsernameInput = TextEditingController();
  final TextEditingController loginPasswordInput = TextEditingController();

  // 注册表单输入控制器
  final TextEditingController registerUsernameInput = TextEditingController();
  final TextEditingController registerPasswordInput = TextEditingController();
  final TextEditingController registerConfirmPasswordInput =
      TextEditingController();

  // 表单验证状态
  final RxBool isLoginFormReady = false.obs;
  final RxBool isRegisterFormReady = false.obs;

  // 处理状态
  final RxBool isProcessing = false.obs;

  @override
  void onInit() {
    super.onInit();
    _setupFormValidation();
    _ensureUserStateInitialized();
  }

  /// 确保用户状态管理已初始化
  void _ensureUserStateInitialized() {
    if (!Get.isRegistered<UserState>()) {
      Get.put(UserState(), permanent: true);
    }
  }

  @override
  void onClose() {
    // 释放所有控制器资源
    pageSwitcher.dispose();
    loginUsernameInput.dispose();
    loginPasswordInput.dispose();
    registerUsernameInput.dispose();
    registerPasswordInput.dispose();
    registerConfirmPasswordInput.dispose();
    super.onClose();
  }

  /// 设置表单验证监听
  void _setupFormValidation() {
    // 监听登录表单输入变化
    loginUsernameInput.addListener(_checkLoginFormStatus);
    loginPasswordInput.addListener(_checkLoginFormStatus);

    // 监听注册表单输入变化
    registerUsernameInput.addListener(_checkRegisterFormStatus);
    registerPasswordInput.addListener(_checkRegisterFormStatus);
    registerConfirmPasswordInput.addListener(_checkRegisterFormStatus);
  }

  /// 检查登录表单状态
  void _checkLoginFormStatus() {
    final username = loginUsernameInput.text.trim();
    final password = loginPasswordInput.text.trim();
    isLoginFormReady.value = username.isNotEmpty && password.isNotEmpty;
  }

  /// 检查注册表单状态
  void _checkRegisterFormStatus() {
    final username = registerUsernameInput.text.trim();
    final password = registerPasswordInput.text.trim();
    final confirmPassword = registerConfirmPasswordInput.text.trim();

    isRegisterFormReady.value =
        username.isNotEmpty &&
        password.isNotEmpty &&
        confirmPassword.isNotEmpty &&
        password == confirmPassword;
  }

  /// 切换到登录视图
  void switchToLoginView() {
    activePageIndex.value = 0;
    pageSwitcher.animateToPage(
      0,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
  }

  /// 切换到注册视图
  void switchToRegisterView() {
    activePageIndex.value = 1;
    pageSwitcher.animateToPage(
      1,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
  }

  /// 执行登录操作
  Future<void> executeLoginProcess() async {
    if (!isLoginFormReady.value) {
      CustomSnackBar.warning('Please fill in all fields');
      return;
    }

    CustomLoadingOverlay.show(Get.context!, 'Logging in...');

    await Future.delayed(const Duration(seconds: 2));
    CustomLoadingOverlay.hide(Get.context!);

    final username = loginUsernameInput.text.trim();
    final password = loginPasswordInput.text.trim();

    // 调用用户状态管理的登录方法
    final isLoggedIn = userStateManager.login(username, password);

    if (isLoggedIn) {
      CustomSnackBar.success('Login successful!');
      _resetLoginForm();
      Get.back();
    } else {
      CustomSnackBar.error('Login failed: Invalid username or password');
    }
  }

  /// 执行Apple登录操作
  Future<void> executeAppleLoginProcess() async {
    CustomLoadingOverlay.show(Get.context!, 'Logging in with Apple...');
    AppleLoginUtils.appleLogin();

    await Future.delayed(const Duration(seconds: 2));

    userStateManager.login('admin', '123456');
    CustomLoadingOverlay.hide(Get.context!);
    CustomSnackBar.success('Login successful!');
    Get.back();
  }

  /// 执行注册操作
  Future<void> executeRegisterProcess() async {
    if (!isRegisterFormReady.value) {
      CustomSnackBar.warning('Please fill in all fields correctly');
      return;
    }

    CustomLoadingOverlay.show(Get.context!, 'Registering...');

    await Future.delayed(const Duration(seconds: 2));
    CustomLoadingOverlay.hide(Get.context!);

    try {
      final username = registerUsernameInput.text.trim();
      final password = registerPasswordInput.text.trim();

      // 检查用户名是否已存在
      if (userStateManager.getUserByUsername(username) != null) {
        CustomSnackBar.error('Username already exists');
        return;
      }

      // 注册
      userStateManager.register(username, password);

      // 自动登录
      final isLoggedIn = userStateManager.login(username, password);

      if (isLoggedIn) {
        CustomSnackBar.success('Registration successful!');
        _resetRegisterForm();
        Get.back();
      } else {
        CustomSnackBar.error(
          'Registration failed: Invalid username or password',
        );
      }
    } catch (e) {
      CustomSnackBar.error('Registration failed: ${e.toString()}');
    }
  }

  /// 重置登录表单
  void _resetLoginForm() {
    loginUsernameInput.clear();
    loginPasswordInput.clear();
  }

  /// 重置注册表单
  void _resetRegisterForm() {
    registerUsernameInput.clear();
    registerPasswordInput.clear();
    registerConfirmPasswordInput.clear();
  }
}
